package io;

import java.io.File;
import java.io.IOException;

public class FileDemo {

    public static void main(String[] args) throws IOException {
        String currentDir = getJavaFilePath(FileDemo.class, "src" + File.separator + "main" + File.separator + "java");
        System.out.println(currentDir);
//        createNewFile("Dynamic:/commonPram/hotchpotch/javaCore/src/main/java/io/a.txt");
        createNewFile("D:/t/t/a.txt");
        deleteFile("D:/t/t/a.txt");


    }

    public static boolean deleteFile(String absolutePath) {
        boolean r = false;
        File f = new File(absolutePath);
        if (!f.exists()) {
            System.out.println("文件不存在" + f.getAbsolutePath());
        } else {
            if (f.isFile()) {
                f.delete();
                System.out.println("文件删除成功->" + f.getAbsolutePath());
            }
            r = true;
        }
        return r;
    }

    public static boolean createNewFile(String absolutePath) {
        boolean r = false;
        File f = new File(absolutePath);
        if (!f.exists()) {
            System.out.println("文件不存在" + f.getAbsolutePath());
            if (f.isAbsolute()) {
                new File(f.getParent()).mkdirs();
            }
            try {
                f.createNewFile();
                System.out.println("文件创建成功->" + f.getAbsolutePath());
                r = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件存在,创建失败! " + f.getAbsolutePath());
        }
        return r;
    }

    /**
     * 得到工程项目中java文件的绝对路径,末尾没有分隔符
     *
     * @param c            类名.class
     * @param srcDirectory java文件所在的源文件夹,默认空为"src/main/java"
     * @return
     */
    public static String getJavaFilePath(Class c, String srcDirectory) {
        String userDir = getProjectPath();
        String packageName = c.getName().toString().substring(0, c.getName().toString().lastIndexOf("."));
        if (!"".equals(srcDirectory)) {
            userDir += File.separator + srcDirectory;
        }else{
            userDir += File.separator + "src" + File.separator + "main" + File.separator + "java";
        }
        userDir = userDir + File.separator + packageName.replace(".", File.separator);
        return userDir;
    }

    /**
     * 调用System.getProperty("user.dir"),末尾没有分隔符
     *
     * @return
     */
    public static String getProjectPath() {
        return System.getProperty("user.dir");
    }

}